package van.planifolia.worktest;

/**
 * Created by Intellij IDEA<br>
 * 线程常用方法的测试类
 *
 * @author Planifolia.Van
 * @version 1.0
 * @date 2022/11/1 16:37
 */
public class ThreadMethods {
    public static void main(String[] args) throws InterruptedException {
        // 我们创建三个线程t1 ，t2
        Thread t1 = new Thread(new MyThread(), "线程A");
        Thread t2 = new Thread(new MyThread(), "线程B");
        Thread t3 = new Thread(new MyThread(), "线程C");

        // 分别设置线程t1 t2的优先级为1，10，尝试让线程2优先执行，并且让t1，t2插队到t3线程前面
        t1.setPriority(1);
        t2.setPriority(10);
        t1.start();
        t2.start();
        // 创建一个守护线程守护到所有线程执行完毕
        Thread thread = new Thread(() -> {
            while (true){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "说：守护");
            }
        }, "守护");
        thread.setDaemon(true);
        thread.start();
        // t1 t2 插队
        t1.join();
        t2.join();
        // t3执行
        t3.start();
    }
}
class MyThread implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            // 我们让线程没休眠0.1s打印依次
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "说：" + i);
        }
    }
}
